package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 查询用户信息
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        model.addAttribute("url",url);
        if(!StringUtils.isEmpty(sso_token)){
            return "redirect:"+url+"?token="+sso_token;
        }
        return "login";
    }

    // 处理登录请求
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("userName") String userName,
                          @RequestParam("passWord") String passWord,
                          @RequestParam("url") String url,
                          HttpServletResponse response){
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(passWord)){
            // 不为空则登录成功,保存用户信息即生成令牌
            String uuid = UUID.randomUUID().toString().replace("_", "");
            stringRedisTemplate.opsForValue().set(uuid,userName);

            // 给浏览器留下登录过的痕迹
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:"+url+"?token="+uuid;

        }else {
            return "login";
        }
    }

}
